package org.nightstudio.common.util.error;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.nightstudio.common.listener.spring.ApplicationContextAccess;
import org.nightstudio.common.util.constant.RequestConstant;
import org.nightstudio.common.util.constant.ViewConstant;
import org.nightstudio.common.util.exception.sys.NightStudioException;
import org.springframework.web.servlet.ModelAndView;

public class ErrorUtil {
	public static void addError(Map<String, Object> model, NightStudioException e) {
		model.put(RequestConstant.PARAM_KEY_ERROR, e);
	}
	
	public static ModelAndView getErrorView(Map<String, Object> model) {
		return new ModelAndView(ViewConstant.ERROR_VIEW, model);
	}
	
	public static ModelAndView getErrorView(Map<String, Object> model, NightStudioException e) {
		addError(model, e);
		return getErrorView(model);
	}
	
	public static ModelAndView getErrorView(NightStudioException e) {
		Map<String, Object> model = new HashMap<String, Object>(1);
		addError(model, e);
		return getErrorView(model);
	}
	
	public static NightStudioException getError(HttpServletRequest request) {
		return (NightStudioException) request.getAttribute(RequestConstant.PARAM_KEY_ERROR);
	}
	
	public static String getErrorMessage(HttpServletRequest request) {
		NightStudioException e = ErrorUtil.getError(request);
		return getErrorMessage(e, request);
	}
	
	public static String getErrorMessage(NightStudioException e) {
		return getErrorMessage(e, null);
	}
	
	public static String getErrorMessage(NightStudioException e, HttpServletRequest request) {
		if (e == null) {
			return "";
		} else {
			if (request != null) {
				return ApplicationContextAccess.getApplicationContext().getMessage(e.getErrorCode().getValue(), e.getArgs(), request.getLocale()); 
			} else {
				return ApplicationContextAccess.getApplicationContext().getMessage(e.getErrorCode().getValue(), e.getArgs(), Locale.getDefault());
			}
		}
	}
}
